package org.chengn.level_middle.context907;

import java.util.Stack;

public class Context907 {
    long res = 0L;
    final int mod = (int)1e9 + 7;
    
    public int sumSubarrayMins(int[] arr) {

        Stack<Integer> stack = new Stack<>();
        long[] arrSum = new long[arr.length + 10];

        for (int i = 0; i < arr.length; ++i) {
            int nowVal = arr[i];
            long thisRes = 0L;
            while (!stack.empty() && arr[stack.peek()] >= nowVal) {
                stack.pop();
            }

            int idx = 0;
            if (!stack.empty()) {
                idx = stack.peek() + 1;
            }

            thisRes = (arrSum[idx] + (long) (i + 1 - idx) * arr[i]) % mod;
            arrSum[i + 1] = thisRes;
            res = (res + thisRes) % mod;
            stack.push(i);
        }

        return (int) res;
    }
}
